package ink.xiaobaibai.config;

import ink.xiaobaibai.filter.MyUsernamePasswordAuthenticationFilter;
import ink.xiaobaibai.provider.MyUsernamePasswordAuthenticationProvider;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.SecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.DefaultSecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * @description: 用户密码登录集成中心
 * @author: 小白白
 * @create: 2021-05-12
 **/

public class MyUsernamePasswordAuthenticationConfig extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> {

    private UserDetailsService userDetailsService;
    private StringRedisTemplate stringRedisTemplate;
    private PasswordEncoder passwordEncoder;

    public MyUsernamePasswordAuthenticationConfig(UserDetailsService userDetailsService, StringRedisTemplate stringRedisTemplate, PasswordEncoder passwordEncoder) {
        this.userDetailsService = userDetailsService;
        this.stringRedisTemplate = stringRedisTemplate;
        this.passwordEncoder = passwordEncoder;
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        //开始拼接 provider+filter
        MyUsernamePasswordAuthenticationFilter filter = new MyUsernamePasswordAuthenticationFilter();
        //虽传null,但内部已有
        filter.setAuthenticationSuccessHandler(null);
        filter.setAuthenticationFailureHandler(null);
        filter.setAuthenticationManager(http.getSharedObject(AuthenticationManager.class));
        filter = this.postProcess(filter);
        MyUsernamePasswordAuthenticationProvider provider =
                new MyUsernamePasswordAuthenticationProvider(this.userDetailsService, this.stringRedisTemplate, this.passwordEncoder);
        http.authenticationProvider(provider)
                .addFilterAfter(filter, UsernamePasswordAuthenticationFilter.class);
    }
}
